package cn.globalph.housekeeper.widgets.loadingview;

import android.animation.ValueAnimator;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;

import com.wang.avi.Indicator;

import java.util.ArrayList;

/**
 * Created by Jack on 2015/10/19.
 */
public class LineScaleIndicator extends Indicator {

    public static final float SCALE = 1.0f;
    public static final int maxAlpha = 204;

    float[] scaleYFloats = new float[]{SCALE,
            SCALE,
            SCALE, SCALE,
            SCALE};

    int[] alpha = new int[]{
            maxAlpha, maxAlpha, maxAlpha
    };

    @Override
    public void draw(Canvas canvas, Paint paint) {
        paint.setColor(Color.argb(255, 255, 173, 41));
        float translateX = getWidth() / 7;
        float translateY = getHeight() / 2;

        for (int i = 0; i < 3; i++) {
            canvas.save();
            paint.setAlpha(alpha[i]);
            canvas.translate((2 + i * 2) * translateX - translateX / 2, translateY);
            canvas.scale(scaleYFloats[i], scaleYFloats[i]);
            RectF rectF = new RectF(-translateX / 2, -translateX * 3 / 4f, translateX / 2, translateX * 3 / 4f);
            canvas.drawRoundRect(rectF, 5, 5, paint);
            canvas.restore();
        }
    }

    @Override
    public ArrayList<ValueAnimator> onCreateAnimators() {
        ArrayList<ValueAnimator> animators = new ArrayList<>();
        long[] delays = new long[]{100, 200, 300, 400, 500};
        for (int i = 0; i < 3; i++) {
            final int index = i;
            ValueAnimator scaleAnim = ValueAnimator.ofFloat(1, 0.5f, 1);
            scaleAnim.setDuration(1000);
            scaleAnim.setRepeatCount(-1);
//            scaleAnim.setInterpolator(new LinearInterpolator());
            scaleAnim.setStartDelay(delays[i]);
            addUpdateListener(scaleAnim, new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    float value = (float) animation.getAnimatedValue();
                    scaleYFloats[index] = value;
                    alpha[index] = (int) ((0.8 * value - 0.1) * 255);
                    postInvalidate();
                }
            });
            animators.add(scaleAnim);
        }
        return animators;
    }

}
